#!/usr/bin/env bash

ngx_http_geoip2_module_version="3.4"
ngx_http_geoip2_module_hash="82d4beef48c260c3568eb0ae56451c95"
openresty_version="1.25.3.1"
openresty_hash="b4f0304bc1d0b34e2a2fb88b3dc30ee1"

set -e -u -x
source ./tasks/helpers.sh

task_working_dir

download "https://openresty.org/download/openresty-$openresty_version.tar.gz" "md5" "$openresty_hash"
extract_download "openresty-$openresty_version.tar.gz"

download "https://github.com/leev/ngx_http_geoip2_module/archive/$ngx_http_geoip2_module_version.tar.gz" "md5" "$ngx_http_geoip2_module_hash"
extract_download "$ngx_http_geoip2_module_version.tar.gz"

cd "openresty-$openresty_version"
patch -p1 < "$SOURCE_DIR/build/patches/openresty-cli.patch"

./configure \
  --prefix="$INSTALL_PREFIX_EMBEDDED/openresty" \
  --with-cc-opt="-I$STAGE_EMBEDDED_DIR/include" \
  --with-ld-opt="-L$STAGE_EMBEDDED_DIR/lib" \
  --error-log-path=stderr \
  --with-ipv6 \
  --with-pcre-jit \
  --without-http_rds_json_module \
  --without-http_rds_csv_module \
  --without-lua_rds_parser \
  --with-stream \
  --with-stream_ssl_module \
  --with-stream_ssl_preread_module \
  --with-http_v2_module \
  --without-mail_pop3_module \
  --without-mail_imap_module \
  --without-mail_smtp_module \
  --with-http_stub_status_module \
  --with-http_realip_module \
  --with-http_addition_module \
  --with-http_auth_request_module \
  --with-http_secure_link_module \
  --with-http_random_index_module \
  --with-http_gzip_static_module \
  --with-http_sub_module \
  --with-http_dav_module \
  --with-http_flv_module \
  --with-http_mp4_module \
  --with-http_gunzip_module \
  --with-threads \
  --with-luajit-xcflags="-DLUAJIT_NUMMODE=2 -DLUAJIT_ENABLE_LUA52COMPAT" \
  --add-module="../ngx_http_geoip2_module-$ngx_http_geoip2_module_version" \
  -j"$NPROC"
make -j"$NPROC"
make install DESTDIR="$STAGE_DIR"
chrpath -d "$STAGE_EMBEDDED_DIR/openresty/nginx/sbin/nginx"
(
  cd "$STAGE_EMBEDDED_DIR/openresty/bin"
  ln -snf ../nginx/sbin/nginx ./openresty
)
mkdir -p "$STAGE_EMBEDDED_DIR/bin"
(
  cd "$STAGE_EMBEDDED_DIR/bin"
  ln -snf ../openresty/bin/resty ./resty
  ln -snf ../openresty/luajit/bin/luajit ./luajit
)
mkdir -p "$STAGE_EMBEDDED_DIR/sbin"
(
  cd "$STAGE_EMBEDDED_DIR/sbin"
  ln -snf ../openresty/nginx/sbin/nginx ./nginx
)

stamp
